<?php
/*
 * Copyright (c) Taras Kudla, 2010
 */

 
class mod_base extends gmodule
  {
    /*
     * Basic module, version 2
     */

    private $MenuElem = null;
    private $MenuParents = null;  
    private $MaxAuthFails = 5;    
    private $RegistrationType  = 0;
    private $FeedbackEmail = "someemail@example.com";    
    private $SendEmailWhenSuccess = true;    
    private $DefaultUserGroup = 2;    
    private $MinEnteredSize = 3;    
    private $UseTermsOfUse  = true;
    private $Applicationstable = "mod_base_regapplications";    
    private $PasswordRecoveryTable = "mod_base_passrecovery";

    public function init()
      {

      }



    public function sysentertaskpanel(){
      }

    public function modeSwitcher()
      {
        $ajaxFile = "ajax.php";

        return $this->lang->get("e53") . ": <a href='" .  $this->api->get("url")  . $ajaxFile . "' >Ajax</a> | <a href='" . $this->api->get("url") . "' >HTML</a>";
      }

    /*
     * Main login function
     */

    public function SysEnter()
      {
         

      }

/*
 * New user registration
 */


    public function Registration()
      {

	$this->api->cms->AddWay("base-registration",null,$this->lang->get("e12"));

        if($this->api->user->CheckUser()){
           return $this->api->errors->Message($this->lang->get("e55"));
        }

	/*
	 * Checking for previous registration applications
	 */ 
	
	if($this->api->session->exists("RegistrationApplication")){
		return $this->api->errors->Message($this->lang->get("e62"));
	}

	/*
	 * Getting all entered data
	 */ 
	$this->api->cms->LoadModule("captcha",$CaptchaModule);
		
	if($this->api->checkPOST("name","lastname","email","password1","password2","check")){
	
		list($name,$lastname,$email) = $this->api->escapePOST("name","lastname","email");
		
		$password=$_POST["password1"]; $password2=$_POST["password2"];
		
		$check = $_POST["check"];
		
		/*
		 * Checking user entered data Неправильний логін чи пароль. Будь ласка, спробуйте ще
		 */
		
		$check = $CaptchaModule->check($check);
		
		if(!$check){			
			print $this->api->errors->Message($this->lang->get("e37"));
		} else 
		if(!$this->CheckEmail($email)){
			print $this->api->errors->Message($this->lang->get("e15"));
		} else 
		if(strlen($firstname)<=$this->MinEnteredSize || strlen($password)<=$this->MinEnteredSize ){
			print $this->api->errors->Message($this->lang->get("e35"));
		} else
		if( strcmp($password,$password2)!=0){	
			print $this->api->errors->Message($this->lang->get("e57"));			
		} else 
		if ($this->UseTermsOfUse==true && !isset($_POST["agree"]) ){
			print $this->api->errors->Message($this->lang->get("e34"));
		} else
		if ($this->api->dbo->select("users","id","where email='".$email."' limit 1 offset 0",_RESULT_BOOL)){
			print $this->api->errors->Message($this->lang->get("e16"));
		} else 
		{
		/*
		 * Adding new user
		 */
		
		/*
		 * Registration for immediatelly method
		 */
		if($this->RegistrationType == _REGISTER_IMMEDIATELY){
			
			$this->api->log->write("new user '".$email."'  registered", _LOG_MESSAGE, _AUTH_LOG);
			
			$this->api->dbo->insert("users",array("email"=>$email,"firstname"=>$firstname,"lastname"=>$lastname,"passwd"=>$this->api->encodeString($password),"groupid"=>$this->DefaultUserGroup,"createdate"=>date("Y-m-d H:i:s")));

                        $this->api->user->SysAuth($e, $p1);
								
		}
		/*
		 * Registration via email 
		 */
		if($this->RegistrationType == _REGISTER_VIA_EMAIL || 
		   $this->RegistrationType == _REGISTER_VIA_ADMINISTRATOR){
			
			/*
			 * Checking for existing applications 
			 */
			
			if($this->api->dbo->select($this->ApplicationsTable,"hash","where email='$email' limit 1 offset 0",_RESULT_BOOL)){
				return $this->api->errors->Message($this->lang->get("e64"));
			}
			
			
			$this->api->log->write("new user '".$email."' made an application for registration",_LOG_MESSAGE,_AUTH_LOG);
			
			$hash=md5($email.microtime(true).rand(0,99));
			
			/*
			 * Building a link
			 *FIXME: In ajax mode link can incorrect
			 */ 
						
			$link = $this->api->cms->GetActionLink("base-registrationconfirm",$hash);
						
			/*
			 * Adding new application
			 */
			
			$this->api->dbo->insert($this->Applicationstable,array("hash"=>$hash,"email"=>$email,"firstname"=>$firstname,"lastname"=>$lastname,"group"=>$this->DefaultUserGroup,"password"=>$this->api->encodeString($password),"createdate"=>date("U") ) );			
			
			$this->api->session->set("RegistrationApplication",true);				
			
			if($this->RegistrationType == _REGISTER_VIA_EMAIL){
			
			/*
			 * Sending a message
			 */ 	
			$messageTemplate = $this->api->view->template("emails/confirm_".$this->api->Language,array("link"=>$link));
			
			/*
			 * TODO: Mail object needed
			 */
			
			//$this->api->mail->sendMessage($email,$messageTemplate);
			
			/*
			 * Printing message
			 */
			 return $this->api->errors->Message($this->lang->get("e58"));
			}
			
			else {
			
			 return $this->api->errors->Message($this->lang->get("e59").($this->SendEmailWhenSuccess?$this->lang->get("e60"):null)  );
			}
		}

		}
	}
	
	if($this->UseTermsOfUse){
		
		$terms=$this->api->view->template("terms/terms_".$this->api->Language);		
	
	} else $terms = null;
	

	return $this->api->view->template("registration",array("imageurl"=>$CaptchaModule->getImageUrl(),"useterms"=>(int)$this->UseTermsOfUse,"terms"=>$terms) );
	
      }

    /*
     * View, Edit User Profile
     */

    public function myprofile()
      {
        $this->api->cms->Way[] = array(
            "v" => $this->lang->get("e49")
        );

        $q = $this->api->dbo->select("users", "*", "where id='" . $this->api->user->GetUserID() . "' limit 1 offset 0");

        $flag = (isset($_GET["flag"]) && is_numeric($_GET["flag"])) ? (int) $_GET["flag"] : 0;

        if ($flag == 1 && $this->api->checkPOST("lname", "fname", "personal"))
          {
            list($name, $lastname, $personal) = $this->api->escapePOST("fname", "lname", "personal");

            $this->api->dbo->update("users", " set firstname='" . $name . "',lastname='" . $lastname . "',personal='" . $personal . "' where id='" . $this->api->user->GetUserID() . "'");

          }

        $q = $this->api->dbo->select("users", "firstname,lastname,passwd,lastdate,lastip,image,avatar,personal", "where id='" . $this->api->user->GetUserID() . "' limit 1 offset 0");

        if ($flag == 2 && ($this->api->checkPOST("Submit") || $this->api->checkPOST("Submit2")))
          {
            if (isset($_FILES["picture"]) && !empty($_FILES["picture"]["tmp_name"]))
              {
                $i = $this->api->file->copyFile("picture", array(
                    "jpg",
                    "jpeg",
                    "gif",
                    "png"
                ));

                $avatar = $this->api->file->cp($i);

                $this->api->file->resizeImage($i, 200);

                $this->api->file->resizeImage($avatar, 100);

                $this->api->file->delete($q[0]["image"]);

                $this->api->file->delete($q[0]["avatar"]);

                $this->api->dbo->update("users", "set image='" . $i . "', avatar='" . $avatar . "' where id='" . $this->api->user->GetUserID() . "'");

                $q[0]["image"] = $i;
              }
            /*
             * Allows to delete even in ajax mode
             */

            if (isset($_POST["Submit2"]))
              {
                $this->api->file->delete($q[0]["image"]);

                $this->api->file->delete($q[0]["avatar"]);

                $this->api->dbo->update("users", "set image='0', avatar='0' where id='" . $this->api->user->GetUserID() . "'");

              }
          }
        $message = null;

        if ($flag == 3 && $this->api->checkPOST("old", "new1", "new2", "Submit"))
          {
            list($old, $new, $new2) = array(
                trim($_POST["old"]),
                trim($_POST["new1"]),
                trim($_POST["new2"])
            );

            $old = $this->api->encodeString($old);

            if ($q[0]["passwd"] != $old)
              {
                $message = $this->lang->get("m45");
              }

            if (strlen($new) <= 5 || strlen($new2) <= 5)
              {
                $message = $this->lang->get("m46");
              }

            if ($new != $new2)
              {
                $message = $this->lang->get("m47");
              }

            if ($message != null)
              {
                $this->api->dbo->update("users", "set passwd='" . $this->api->encodeString($new) . "' where id='" . $this->api->user->GetUserID() . "'");

                $flag = 0;

                $message = $this->lang->get("m48");

              }

          }

        $img = $this->api->file->GetFoto($q[0]["image"]);

        return $this->api->view->template("me", array(
            "img" => $img,
            "flag" => $flag,
            "data" => &$q,
            "useMessage" => ($message != null) ? 1 : 0,
            "message" => "<b>" . $message . "</b>"
        ));

      }

    /*
     * Additional functions
     */

    private function CheckEmail($string){
    	
    	return preg_match("/^[^@]+@[^@]+\.[^@]+$/i", $string, $trash);
    }	


    private function genpassword($length = 9, $strength = 9)
      {

      }


    public function ForgotPassword()
      {


      }
    
	public function changeLanguage(){
		if (isset($_GET["l"]) && in_array($_GET["l"],$this->api->get("syslanguages")) ){
			$this->api->session->set("language",$this->api->escapeString($_GET["l"]));
			$this->api->cms->redirect();
		}
		$language = $this->api->getlanguage();
		return $this->api->view->template("changeLanguage", array("language" => $language));
	}

    public function GetRoad()
      {	      	
      	return $this->api->cms->BuildWay();
      }


    
    /*
     * Main feedback function, you change 
     */
    	
    public function Feedback()
      {
      
        $this->api->cms->AddWay("base-Feedback",null,$this->lang->get("e44") );

        if($this->api->session->exists("FeedbackMessage")){

            return $this->api->errors->Message($this->lang->get("e72"));
        }


        /*
         * Information check
         */
        $this->api->cms->LoadModule("captcha",$CaptchaModule);
        if($this->api->checkPOST("name","text","Submit","check") ){

            list($name,$text)=$this->api->escapePOST("name","text");

            if(strlen($name)<=0 || strlen($text)<=0 ){
                print $this->api->errors->Message($this->lang->get("e35") );
            } else if(!$CaptchaModule->check($_POST["check"])){
                print $this->api->errors->Message($this->lang->get("e37") );
            } else {

                $this->api->LoadLibrary("Mail");
                $mail=new Mail();
                $mail->To = $this->FeedbackEmail;
                $mail->Subject = $this->lang->get("e66");
                $mail->addHeader("X-Mailer", "Azaria Web Mailer");
                $mail->addHeader("MIME-Version","1.0");
                $mail->addHeader("Content-type", "text/html; charset=utf-8");
                $mail->Message=$this->api->view->template("emails/feedback",array("name"=>$name,"created"=>
                        date("Y-m-d H:i:s"),"text"=>&$text) );
                if($mail->send()){
                    $this->api->session->set("FeedbackMessage",true);
                    return $this->api->errors->Message($this->lang->get("e70") );
                } else {
                    $this->api->log->write("base","Cannot send feedback message",_ERROR_LOG,_LOG_ERROR);
                    return $this->api->errors->Message($this->lang->get("e70") );
                }
            }
        }
        return $this->api->view->template("feedback",array("imageurl"=>$CaptchaModule->getImageUrl()) );
      }
   /*
    * Menu building tool
    */
    public function GetMyMenu()
      {
        $sql = "where lang='" . $this->api->getlanguage() . "'  and term IN ( select hash from levellinks where level = '" . $this->api->get("accesslevel") . "' and hash IN (" . "'" . implode("','", $this->api->user->GetUserAccess()) . "'" . ") ) order by weight desc ";
        $Query = $this->api->dbo->select("langterms", "id,value,parent,term,alias,param,url", $sql);
        $parents = array();
        $elem = array();
        /*
         * Searching for all parents
         */
        $i = 0;
        while ($i < count($Query))
          {
            $parent = $Query[$i]["parent"];
            $id     = $Query[$i]["id"];
            if (!isset($parents[$parent]))
                $parents[$parent] = array();
	    if( empty($Query[$i]["url"])){
		$elem[$id] = "<a href=\"".$this->api->cms->getactionlink($Query[$i]["alias"], null)."\">".$Query[$i]["value"]."</a>";
	    } else {
		$elem[$id] = "<a href=\"".$Query[$i]["url"]."\">".$Query[$i]["value"]."</a>";
	    }
            
            array_push($parents[$parent], $id);
            $i++;
          }
        $this->MenuParents = $parents; 
        $this->MenuElem = $elem;

        /*
         * Building a tree
         */
        print $this->MenuTree();
      }

    private function MenuTree($parent = 0, $lvl = 0)
      {
        $m = null;
        $lvl++;
        if (isset($this->MenuParents[$parent]))
          {
            $m .= "<ul>";
            foreach ($this->MenuParents[$parent] as $k => $v)
              {
                $m .= "<li>" . $this->MenuElem[$v] . "";
                $m .= $this->MenuTree($v, $lvl);
                $m .= "</li>";
                $lvl--;
              }
            $m .= "</ul>";
          }
        return $m;
      }
    	 
    public function GetSitemap()
      {
        return "<div id='pagev'>" . $this->lang->get("e47") . "</div>" . $this->GetMyMenu();
      }
  /*
   * Basic system options editing tool
   */ 
   
   public function options(){
   	

   }
   
    public function install()
      {

      }

    public function uninstall()
      {
      

      
      }
  }
?>
